package com.dudu.common.ext

import android.os.SystemClock
import android.view.View

/**
 * <pre>
 *     author : dzc
 *     time   : 2024/11/07
 *     desc   : View扩展函数
 * </pre>
 */

/**
 * 防抖动点击事件
 */
fun View.singleClick(
    interval: Int = 1000,
    block: (view: View) -> Unit
) {
    this.setOnClickListener(SingleClickListener(interval, block))
}

class SingleClickListener(
    private var interval: Int,
    private var block: (view: View) -> Unit
) : View.OnClickListener {

    private var mTag = -11

    override fun onClick(v: View) {
        val curTime = SystemClock.elapsedRealtime()
        System.currentTimeMillis()
        val tag: Any? = v.getTag(mTag)
        if (tag == null) {
            v.setTag(mTag, curTime)
            block.invoke(v)
            return
        }

        val lastClickTime = tag as Long
        val canClick = curTime - lastClickTime > interval
        if (canClick) {
            block.invoke(v)
            v.setTag(mTag, curTime)
        }
    }
}